﻿using fmtx.Framework.DALFactory;
using fmtx.Framework.DESC;
using fmtx.Framework.Web;
using SYH.DataAccess;
using SYH.Domain.Applicaton;
using SYH.Domain.ViewModels.Applicaton;
using SYH.IBLL;
using SYH.IWebBLL;
using SYH.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SYH.Web.Controllers.Apis
{
    public class ILoginController : PubController
    {
        private readonly IEntityRepository<ApplicationLog> dbLog;
        private readonly IEntityRepository<SystemUser> _UserService;
        private readonly IEntityRepository<SystemLoginInfo> _LoginInfoService;
        public ILoginController(
            IEntityRepository<SystemUser> UserService,
            IEntityRepository<ApplicationLog> _dbLog,
            IEntityRepository<SystemLoginInfo> LoginInfoService
            )
        {
            _UserService = UserService;
            _LoginInfoService = LoginInfoService;
            dbLog = _dbLog;
        }


        // GET: ILogin

        /// <summary>
        /// 处理登录信息
        /// </summary>
        /// <param name="logonQueryJson"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string loginName, string password)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            WebCookieHelper.RemoveCookie();
            SystemUser suser = null;
            if (suser == null)
            {
                password = DESCHandler.MD5_32(password);
                suser = _UserService.GetBo(w => w.Name == loginName && w.Password == password);
            }
            if (suser != null)
            {
                if (suser.IsDel)
                {
                    return Json(new ResultVM(1, "该账户已被禁用！！"));
                }
                else
                {
                    var logininfo = new SystemLoginInfo
                    {
                        UID = suser.ID,
                        LoginDate = DateTime.Now,
                        Ip = GetWebClientIp()
                    };
                    _LoginInfoService.SaveBo(logininfo);
                    var user = LoginService.SetLogin(suser);
                    return Json(new ResultVM(0, "登录成功！") { data = user });
                }
            }
            else
            {
                return Json(new ResultVM(1, "用户名密码不正确！！"));
            }
        }

        /// <summary>
        /// 获取当前用ip
        /// </summary>
        /// <returns></returns>
        private string GetWebClientIp()
        {
            string userIP = "未知IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP 
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;
        }

        /// <summary>
        /// 创建超级管理员
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateAdmin()
        {
            var root = _UserService.GetBo(w => w.Name == "root");
            if (root == null)
            {
                _UserService.SaveBo(new SystemUser { ID = Guid.NewGuid(), Password = DESCHandler.MD5_32("System.Linq"),Name = "root", ChineseName = "超级管理员", GroupCode = GroupCode.Administrator });
                _UserService.SaveBo(new SystemUser { ID = Guid.NewGuid(), Password = DESCHandler.MD5_32("admin"),Name = "admin", ChineseName = "超级管理员", GroupCode = GroupCode.Administrator });
            }
            return null;
        }
    }
}